/*
 * File Name：HttpHelper.java
 * Copyright：Copyright 2008 - 2013 CiWong.Inc. All Rights Reserved.
 * Description： HttpHelper.java
 * Modify By：jejun
 * Modify Date：2012-11-18
 * Modify Type：Add
 */
package com.ciwong.libs.utils;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.DeleteMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.PutMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.json.JSONObject;

import com.google.gson.Gson;

/**
 * http辅助类
 * 
 * @author jejun
 * @version ciwong v.1.0 2012-11-18
 * @since ciwong v.1.0
 */
public class HttpHelper
{
    /**
     * 
     * 初始化GET请求
     * 
     * @param params
     *            请求参数
     * @param url
     *            请求地址
     * @param headers
     *            请求头
     * @return GetMethod
     * @throws Exception
     *             Exception
     */
    public static GetMethod getGetConnection(Map<String, String> params,
            String url, Map<String, String> headers) throws Exception
    {
        StringBuilder sb = new StringBuilder();
        sb.append(concatUrl(params, url));
        String connUrl = null;
        GetMethod mGetMethod = null;
        connUrl = sb.toString();
        if (connUrl != null)
        {
            mGetMethod = new GetMethod(connUrl);
            initRequest(mGetMethod, headers);
        }
        return mGetMethod;
    }

    /**
     * 初始化Post请求实例
     * 
     * @param params
     *            请求参数
     * @param url
     *            请求地址
     * @param headers
     *            请求头
     * @return PostMethod
     * @throws Exception
     *             Exception
     */
    public static PostMethod getPostConnection(Map<String, String> params,
            String url, Map<String, String> headers) throws Exception
    {
        String connUrl = url;
        PostMethod mPostMethod = null;
        if (connUrl != null)
        {
            mPostMethod = new PostMethod(connUrl);
            if (params != null && !params.isEmpty())
            {
                int index = 0;
                NameValuePair[] bodyParams = new NameValuePair[params.size()];
                for (String key : params.keySet())
                {
                    bodyParams[index] = new NameValuePair();
                    bodyParams[index].setName(key);
                    bodyParams[index].setValue(params.get(key));
                    index++;
                }
                mPostMethod.setRequestBody(bodyParams);
                CWLog.i("AsyncHttpRequest",
                        "PostMethod.bodyParams:" + params.toString());
            }
            initRequest(mPostMethod, headers);
        }
        return mPostMethod;
    }

    /**
     * 初始化Post请求实例
     * 
     * @param params
     *            请求参数
     * @param url
     *            请求地址
     * @param headers
     *            请求头
     * @param isRestJsonApi
     *            是否请求Json对象
     * @return PostMethod
     * @throws Exception
     */
    public static PostMethod getPostConnection(Map<String, String> params,
            String url, Map<String, String> headers, boolean isRestJsonApi)
            throws Exception
    {
        String connUrl = url;
        PostMethod mPostMethod = null;
        if (isRestJsonApi)
        {
            if (connUrl != null)
            {
                mPostMethod = new PostMethod(connUrl);
                if (params != null && !params.isEmpty())
                {
                    for (String key : params.keySet())
                    {
                        StringRequestEntity requestEntity = new StringRequestEntity(
                                params.get(key),
                                "application/json; charset=UTF-8", null);
                        mPostMethod.setRequestEntity(requestEntity);
                    }
                }
                if (headers == null)
                {
                    headers = new HashMap<String, String>();
                }
                headers.put("Content-Type", "application/json");
                initRequest(mPostMethod, headers);
            }
        }
        else
        {
            mPostMethod = getPostConnection(params, connUrl, headers);
        }
        return mPostMethod;
    }

    /**
     * 初始化Post请求实例
     * 
     * @param params
     *            请求参数
     * @param url
     *            请求地址
     * @param headers
     *            请求头
     * @param isRestJsonApi
     *            是否请求Json对象
     * @return PostMethod
     * @throws Exception
     */
    public static PostMethod getPostConnection(Object objectParams,
            Map<String, String> params, String url,
            Map<String, String> headers, boolean isRestJsonApi)
            throws Exception
    {
        String connUrl = url;
        PostMethod mPostMethod = null;
        if (isRestJsonApi)
        {
            if (connUrl != null)
            {
                mPostMethod = new PostMethod(connUrl);
                if (params != null && !params.isEmpty())
                {
                    for (String key : params.keySet())
                    {
                        StringRequestEntity requestEntity = new StringRequestEntity(
                                params.get(key),
                                "application/json; charset=UTF-8", null);
                        mPostMethod.setRequestEntity(requestEntity);
                    }
                }
                if (objectParams != null)
                {
                    if (objectParams instanceof JSONObject)
                    {
                        String json = URLEncoder.encode(
                                objectParams.toString(), "UTF-8");
                        int index = json.indexOf("+");
                        if (index != -1)
                        {
                            json = json.replace("+", "%20");
                        }
                        CWLog.i("AsyncHttpRequest", "PutMethod.objectParams:"
                                + json);
                        mPostMethod.setRequestBody(json);
                    }
                    else
                    {
                        Gson gson = new Gson();
                        String json = URLEncoder.encode(
                                gson.toJson(objectParams).toString(), "UTF-8");
                        int index = json.indexOf("+");
                        if (index != -1)
                        {
                            json = json.replace("+", "%20");
                        }
                        CWLog.i("AsyncHttpRequest", "PostMethod.objectParams:"
                                + json);
                        mPostMethod.setRequestBody(json);
                    }
                }
                if (headers == null)
                {
                    headers = new HashMap<String, String>();
                }
                headers.put("Content-Type", "application/json");
                initRequest(mPostMethod, headers);
            }
        }
        else
        {
            mPostMethod = getPostConnection(params, connUrl, headers);
        }
        return mPostMethod;
    }

    /**
     * 初始化Put请求实例
     * 
     * @param params
     *            请求参数
     * @param url
     *            请求地址
     * @param headers
     *            请求头
     * @return PutMethod
     * @throws Exception
     *             Exception
     */
    public static PutMethod getPutConnection(String url,
            Map<String, String> headers) throws Exception
    {
        String connUrl = url;
        PutMethod mPutMethod = null;
        if (connUrl != null)
        {
            mPutMethod = new PutMethod(connUrl);
            initRequest(mPutMethod, headers);
        }
        return mPutMethod;
    }

    /**
     * 初始化Put请求实例
     * 
     * @param params
     *            请求参数
     * @param url
     *            请求地址
     * @param headers
     *            请求头
     * @param isRestJsonApi
     *            是否请求Json对象
     * @return PutMethod
     * @throws Exception
     */
    public static PutMethod getPutConnection(Object objectParams, String url,
            Map<String, String> headers, boolean isRestJsonApi)
            throws Exception
    {
        String connUrl = url;
        PutMethod mPutMethod = null;
        if (isRestJsonApi)
        {
            if (connUrl != null)
            {
                mPutMethod = new PutMethod(connUrl);
                if (objectParams != null)
                {
                    if (objectParams instanceof JSONObject)
                    {
                        String json = URLEncoder.encode(
                                objectParams.toString(), "UTF-8");
                        int index = json.indexOf("+");
                        if (index != -1)
                        {
                            json = json.replace("+", "%20");
                        }
                        CWLog.i("AsyncHttpRequest", "PutMethod.objectParams:"
                                + json);
                        mPutMethod.setRequestBody(json);
                    }
                    else
                    {
                        Gson gson = new Gson();
                        String json = URLEncoder.encode(
                                gson.toJson(objectParams).toString(), "UTF-8");
                        int index = json.indexOf("+");
                        if (index != -1)
                        {
                            json = json.replace("+", "%20");
                        }
                        CWLog.i("AsyncHttpRequest", "PutMethod.objectParams:"
                                + json);
                        mPutMethod.setRequestBody(json);
                    }
                }
                if (headers == null)
                {
                    headers = new HashMap<String, String>();
                }
                headers.put("Content-Type", "application/json");
                initRequest(mPutMethod, headers);
            }
        }
        else
        {
            mPutMethod = getPutConnection(connUrl, headers);
        }
        return mPutMethod;
    }

    /**
     * 
     * 初始化DELETE请求
     * 
     * @param params
     *            请求参数
     * @param url
     *            请求地址
     * @param headers
     *            请求头
     * @return GetMethod
     * @throws Exception
     *             Exception
     */
    public static DeleteMethod getDeleteConnection(Map<String, String> params,
            String url, Map<String, String> headers) throws Exception
    {
        StringBuilder sb = new StringBuilder();
        sb.append(concatUrl(params, url));
        String connUrl = null;
        DeleteMethod mDeleteMethod = null;
        connUrl = sb.toString();
        if (connUrl != null)
        {
            mDeleteMethod = new DeleteMethod(connUrl);
            initRequest(mDeleteMethod, headers);
        }
        return mDeleteMethod;
    }

    /**
     * 拼接请求地址
     * 
     * @param params
     *            请求参数
     * @param url
     *            请求地址
     * @return 拼接后的请求地址
     */
    public static String concatUrl(Map<String, String> params, String url)
    {
        if (params != null && !params.isEmpty())
        {
            StringBuilder sb = new StringBuilder();
            boolean hasAdd = true;
            if (url.lastIndexOf("?") == url.length() - 1)
            {
                hasAdd = false;
            }
            else if (url.lastIndexOf("&") == url.length() - 1)
            {
                hasAdd = false;
            }
            int index = 0;
            for (String key : params.keySet())
            {
                if (index != 0 || hasAdd)
                {
                    sb.append("&");
                    hasAdd = false;
                }
                sb.append(key);
                sb.append("=");
                sb.append(params.get(key));
                index++;
            }
            return url + sb.toString();
        }
        return url;
    }

    /**
     * 初始化http请求
     * 
     * @param request
     *            HttpURLConnection
     * @param headers
     *            请求头
     */
    public static void initRequest(HttpMethod request,
            Map<String, String> headers)
    {
        request.addRequestHeader("Content-Type",
                "application/x-www-form-urlencoded; charset=utf-8");
        request.setRequestHeader("Charset", "UTF-8");
        // StringBuffer sb = new StringBuffer();
        // sb.append("Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; ");
        // sb.append(".NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)");
        // request.addRequestHeader("User-Agent", sb.toString());
        request.setRequestHeader("Accept-Encoding", "GZIP, deflate");
        if (headers != null)
        {
            Set<String> keySet = headers.keySet();
            for (String key : keySet)
            {
                request.setRequestHeader(key, headers.get(key));
            }
        }
    }
}